<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="utf-8">
  
  
  
  <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
  <title>
    Effective Java 阅读笔记（之创建和销毁对象） |
    
    M_W_Q</title>
  
    <link rel="shortcut icon" href="/bolg/favicon.ico">
  
  <link rel="stylesheet" href="/bolg/css/style.css">
  
    <link rel="stylesheet" href="/bolg/fancybox/jquery.fancybox.min.css">
  
  <script src="/bolg/js/pace.min.js"></script>
</head>

<body>
<main class="content">
  <section class="outer">
  

<article id="post-Effective Java 阅读笔记（之创建和销毁对象）" class="article article-type-post" itemscope itemprop="blogPost" data-scroll-reveal>
  
  <div class="article-inner">
    
      <header class="article-header">
        
  
    <h1 class="article-title" itemprop="name">
      Effective Java 阅读笔记（之创建和销毁对象）
    </h1>
  
  




      </header>
    

    
      <div class="article-meta">
        <a href="/bolg/2019/10/21/Effective%20Java%20%E9%98%85%E8%AF%BB%E7%AC%94%E8%AE%B0%EF%BC%88%E4%B9%8B%E5%88%9B%E5%BB%BA%E5%92%8C%E9%94%80%E6%AF%81%E5%AF%B9%E8%B1%A1%EF%BC%89/" class="article-date">
  <time datetime="2019-10-21T14:06:44.887Z" itemprop="datePublished">2019-10-21</time>
</a>
        
      </div>
    

    
      
    <div class="tocbot"></div>





    

    <div class="article-entry" itemprop="articleBody">
      


      

      
        <h2 id="引言"><a href="#引言" class="headerlink" title="引言"></a><strong>引言</strong></h2><p>本博客的内容完全是为记录自己的一些读书感悟，如果喜欢可以进行阅读如有问题请指正，谢谢。</p>
<h2 id="思考"><a href="#思考" class="headerlink" title="思考"></a><strong>思考</strong></h2><ol>
<li>什么是构造器，什么是静态工厂方法？</li>
<li>什么时候用构造器，什么时候用静态工厂方法？</li>
</ol>
<h2 id="静态工厂方法和构造器"><a href="#静态工厂方法和构造器" class="headerlink" title="静态工厂方法和构造器"></a><strong>静态工厂方法和构造器</strong></h2><p><strong>静态工厂方法的优点：</strong></p>
<ol>
<li>静态方法是有名称的，有具体的名称更易于使用者去阅读和了解其功能。如果我需要多个构造器时，使用静态工厂方法可能是最好的。多个构造器除了参数类型等区分不同的功能再没有其他的方式，极易用错。但是静态的构工厂方法可以为每一个提供不同的名称，很容易区分。这种情况使用静态工厂是个好的实现方式。</li>
<li>静态工厂方法了解加载机制的都知道，它不会再每一次调用时都构建一个新的对象，对于频繁调用时是一个不错的方式。</li>
<li>静态工厂方法有返回值，在某种用途上我们能够更好的实现。例如后面的构建器。</li>
<li>实例化参数类型时更加的简洁明了。</li>
</ol>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//实例化时</span></span><br><span class="line">Map&lt;String, List&lt;String&gt;&gt; map = <span class="keyword">new</span> HashMap&lt;String, List&lt;String&gt;&gt;();</span><br><span class="line"><span class="comment">//Google Guava提供的静态实例化方法</span></span><br><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">static</span>&lt;K, V&gt; HashMap&lt;K, V&gt; <span class="title">newHashMap</span><span class="params">()</span></span>&#123;</span><br><span class="line">	reutrn <span class="keyword">new</span> HashMap&lt;K, V&gt;();</span><br><span class="line">&#125;</span><br><span class="line"><span class="comment">//实例化时</span></span><br><span class="line">Map&lt;String, List&lt;String&gt;&gt; map = Maps.newHashMap();</span><br></pre></td></tr></table></figure>

<p><strong>静态工厂方法的缺点：</strong></p>
<ol>
<li>类如果没有构造器，就不能被子类去类化。</li>
<li>它们与其他的静态方法没什么区别。API文档中不会提供静态方法的说明，有时候你可能只看文档无法知道如何实例化一个类（当然看源码很容易就知道了）</li>
</ol>
<h2 id="使用构建器"><a href="#使用构建器" class="headerlink" title="使用构建器"></a><strong>使用构建器</strong></h2><ol>
<li>使用构造器是解决静态工厂和构造器的局限性，它们不能很好的扩展到大量的可选择参数。</li>
<li>普通的要灵活的使用构造的参数个数可能要写大量的构造器去处理，相当的繁琐。</li>
<li>前期可能使用的参数较少感觉使用构建器反而更复杂，但是后期扩展时很方便。</li>
</ol>
<p>构建器的实现：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br></pre></td><td class="code"><pre><span class="line">	public class Build &#123;</span><br><span class="line"></span><br><span class="line">    private String name;</span><br><span class="line">    private Integer age;</span><br><span class="line">    private String desc;</span><br><span class="line"></span><br><span class="line">    public static class BuildForm &#123;</span><br><span class="line">        private String name;</span><br><span class="line">        private Integer age;</span><br><span class="line">        private String desc;</span><br><span class="line"></span><br><span class="line">        public BuildForm() &#123;</span><br><span class="line"></span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        public BuildForm nameBuild(String name) &#123;</span><br><span class="line">            this.name = name;</span><br><span class="line">            return this;</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        public BuildForm ageBuild(Integer age) &#123;</span><br><span class="line">            this.age = age;</span><br><span class="line">            return this;</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        public BuildForm descBuild(String decs) &#123;</span><br><span class="line">            this.desc = decs;</span><br><span class="line">            return this;</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        public Build buildData() &#123;</span><br><span class="line">            return new Build(this);</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">    &#125;</span><br><span class="line">    //创建私有构造器防止调用默认构造器处理和处理内部赋值</span><br><span class="line">    private Build(BuildForm buildForm)&#123;</span><br><span class="line">        this.name = buildForm.name;</span><br><span class="line">        this.age = buildForm.age;</span><br><span class="line">        this.desc = buildForm.desc;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    @Override</span><br><span class="line">    public String toString() &#123;</span><br><span class="line">        return &quot;Build&#123;&quot; +</span><br><span class="line">                &quot;name=&apos;&quot; + name + &apos;\&apos;&apos; +</span><br><span class="line">                &quot;, age=&quot; + age +</span><br><span class="line">                &quot;, desc=&apos;&quot; + desc + &apos;\&apos;&apos; +</span><br><span class="line">                &apos;&#125;&apos;;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>构建器的使用：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br></pre></td><td class="code"><pre><span class="line">public class Main &#123;</span><br><span class="line"></span><br><span class="line">    public static void main(String[] argv) &#123;</span><br><span class="line">        Build buildOne = new Build.BuildForm()</span><br><span class="line">        .nameBuild(&quot;AA&quot;)</span><br><span class="line">        .buildData();</span><br><span class="line">        Build buildTwo = new Build.BuildForm()</span><br><span class="line">        .nameBuild(&quot;BB&quot;)</span><br><span class="line">        .ageBuild(12)</span><br><span class="line">        .buildData();</span><br><span class="line">        Build buildThree = new Build.BuildForm()</span><br><span class="line">        .nameBuild(&quot;CC&quot;)</span><br><span class="line">        .ageBuild(12)</span><br><span class="line">        .descBuild(&quot;啊哈哈&quot;)</span><br><span class="line">        .buildData();</span><br><span class="line"></span><br><span class="line">        System.out.println(buildOne.toString());</span><br><span class="line">        System.out.println(buildTwo.toString());</span><br><span class="line">        System.out.println(buildThree.toString());</span><br><span class="line"></span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>测试结果如下：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">Build&#123;name=&apos;AA&apos;, age=null, desc=&apos;null&apos;&#125;</span><br><span class="line">Build&#123;name=&apos;BB&apos;, age=12, desc=&apos;null&apos;&#125;</span><br><span class="line">Build&#123;name=&apos;CC&apos;, age=12, desc=&apos;啊哈哈&apos;&#125;</span><br></pre></td></tr></table></figure>

<p>以上就是一个简单的构建器，大家可以根据自己的需求去使用。</p>
<h2 id="单例属性的强化"><a href="#单例属性的强化" class="headerlink" title="单例属性的强化"></a><strong>单例属性的强化</strong></h2><p><strong>私有的构造器</strong></p>
<p>就如同我上面代码中写到的，如果不使用私有的构造器去处理类，虽然我们的实现是单例的，但是使用者完全可以使用默认的构造器去创建出来新的对象，有时候就违背我们的初衷。</p>
<p><strong>枚举的方式</strong></p>
<p>我们可以使用枚举的方式去创建一个单例模式，这样就不会出现上述的情况。创建的方式如下代码：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br></pre></td><td class="code"><pre><span class="line">//创建一个类</span><br><span class="line">public class Factory &#123;</span><br><span class="line">&#125;</span><br><span class="line">//枚举的方式实例化类</span><br><span class="line">public enum  EnumFactory &#123;</span><br><span class="line">    DATE;</span><br><span class="line">    private Factory factory;</span><br><span class="line">    public void buildSingleton()&#123;</span><br><span class="line">        factory = new Factory();</span><br><span class="line">    &#125;</span><br><span class="line">    public Factory getFactory()&#123;</span><br><span class="line">        return factory;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line">//类的使用</span><br><span class="line">public class Main &#123;</span><br><span class="line"></span><br><span class="line">    public static void main(String[] argv) &#123;</span><br><span class="line">        Factory factory = EnumFactory.DATE.getFactory();</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>三种单例的创建模式，枚举的方式可能是现在做好的方法。</p>
<h2 id="对象的销毁"><a href="#对象的销毁" class="headerlink" title="对象的销毁"></a><strong>对象的销毁</strong></h2><p><strong>内存泄露</strong></p>
<p>对象有创建必然存在销毁，java提供有自己的垃圾回收机制。但是并不代表java不会出现内存泄露。所以我们需要消除过期的对象引用，若过期的对象引用一直存在垃圾回收器就不会去回收资源。一般这种情况发生在引用缓存中。开发中要注意这类情况。下面是三种容易发生内存泄露的情况。</p>
<ol>
<li>无意识的泄露，一般是代码考虑不周全导致，没有考虑泄露的意识。</li>
<li>缓存中存放的对象，一般需要去维护，不然容易出现泄露。</li>
<li>监听器和回调，这种情况一般是需要维护对象的长期有效的，但是使用完成如果不进行注销就会出现泄露。</li>
</ol>
<p><strong>避免使用终结方法</strong></p>
<p>java有提供终结方法来让开发者去终结，但是终结方法的线程优先级极低，我们并不能去确定终结方法一定会执行，有不能确定终结方法执行的时间。当然有些情况是需要去使用终结方法的，例如流的关闭，一般要配合try….finally来使用。</p>
<h2 id="结束语"><a href="#结束语" class="headerlink" title="结束语"></a><strong>结束语</strong></h2><p>一些简单的介绍，如果要很好的了解建议大家亲自去看看这本书。希望浅薄的理解能对你的开发有帮助。</p>

      
    </div>
    <footer class="article-footer">
      <a data-url="http://m_aleen.gitee.io/bolg/2019/10/21/Effective%20Java%20%E9%98%85%E8%AF%BB%E7%AC%94%E8%AE%B0%EF%BC%88%E4%B9%8B%E5%88%9B%E5%BB%BA%E5%92%8C%E9%94%80%E6%AF%81%E5%AF%B9%E8%B1%A1%EF%BC%89/" data-id="ck32z8yte000069db5ycr39vj"
         class="article-share-link">Share</a>
      
    </footer>

  </div>

  
    
  <nav class="article-nav">
    
      <a href="/bolg/2019/10/21/%E5%8F%AF%E9%87%8D%E5%A4%8D%E6%89%A7%E8%A1%8C/" class="article-nav-link">
        <strong class="article-nav-caption">Newer posts</strong>
        <div class="article-nav-title">
          
            可重复执行
          
        </div>
      </a>
    
    
      <a href="/bolg/2019/10/21/%E8%B7%A8%E5%9F%9F%E9%97%AE%E9%A2%98/" class="article-nav-link">
        <strong class="article-nav-caption">Olde posts</strong>
        <div class="article-nav-title">跨域问题</div>
      </a>
    
  </nav>


  

  
    
  

</article>



</section>
  <footer class="footer">
  <div class="outer">
    <div class="float-right">
      <ul class="list-inline">
  
    <li><i class="fe fe-smile-alt"></i> <span id="busuanzi_value_site_uv"></span></li>
  
    <li><i class="fe fe-bookmark"></i> <span id="busuanzi_value_page_pv"></span></li>
  
</ul>
    </div>
    <ul class="list-inline">
      <li>&copy; 2019 M_W_Q</li>
      <li>Powered by <a href="http://hexo.io/" target="_blank">Hexo</a></li>
      <li>Theme  <a href="https://github.com/zhwangart/hexo-theme-ocean" target="_blank" rel="noopener">Ocean</a></li>
    </ul>
  </div>
</footer>

</main>

<aside class="sidebar sidebar-specter">
  
    <button class="navbar-toggle"></button>
<nav class="navbar">
  
    <div class="logo">
      <a href="/bolg/"><img src="/bolg/images/hexo.svg" alt="M_W_Q"></a>
    </div>
  
  <ul class="nav nav-main">
    
      <li class="nav-item">
        <a class="nav-item-link" href="/bolg/">Home</a>
      </li>
    
      <li class="nav-item">
        <a class="nav-item-link" href="/bolg/archives">Archives</a>
      </li>
    
      <li class="nav-item">
        <a class="nav-item-link" href="/bolg/gallery">Gallery</a>
      </li>
    
      <li class="nav-item">
        <a class="nav-item-link" href="/bolg/about">About</a>
      </li>
    
    <li class="nav-item">
      <a class="nav-item-link nav-item-search" title="搜索">
        <i class="fe fe-search"></i>
        Search
      </a>
    </li>
  </ul>
</nav>
<nav class="navbar navbar-bottom">
  <ul class="nav">
    <li class="nav-item">
      <div class="totop" id="totop">
  <i class="fe fe-rocket"></i>
</div>
    </li>
    <li class="nav-item">
      
        <a class="nav-item-link" target="_blank" href="/bolg/atom.xml" title="RSS Feed">
          <i class="fe fe-feed"></i>
        </a>
      
    </li>
  </ul>
</nav>
<div class="search-form-wrap">
  <div class="local-search local-search-plugin">
  <input type="search" id="local-search-input" class="local-search-input" placeholder="Search...">
  <div id="local-search-result" class="local-search-result"></div>
</div>
</div>
  </aside>
  <script src="/bolg/js/jquery-2.0.3.min.js"></script>
<script src="/bolg/js/jquery.justifiedGallery.min.js"></script>
<script src="/bolg/js/lazyload.min.js"></script>
<script src="/bolg/js/busuanzi-2.3.pure.min.js"></script>

  <script src="/bolg/fancybox/jquery.fancybox.min.js"></script>



  <script src="/bolg/js/tocbot.min.js"></script>
  <script>
    // Tocbot_v4.7.0  http://tscanlin.github.io/tocbot/
    tocbot.init({
      tocSelector: '.tocbot',
      contentSelector: '.article-entry',
      headingSelector: 'h1, h2, h3, h4, h5, h6',
      hasInnerContainers: true,
      scrollSmooth: true,
      positionFixedSelector: '.tocbot',
      positionFixedClass: 'is-position-fixed',
      fixedSidebarOffset: 'auto',
    });
  </script>


<script src="/bolg/js/ocean.js"></script>

</body>
</html>